/*
 * @Author: taosong 2289713738@qq.com
 * @Date: 2023-12-23 18:45:32
 * @LastEditors: taosong 2289713738@qq.com
 * @LastEditTime: 2023-12-23 20:22:43
 * @FilePath: \ele-h5\src\use\useDebounce.ts
 * @Description:
 *
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved.
 */
// interface IDebounce<T> {
//   (...args: T[]): void | Promise<void>
// }

// import type { Ref } from "vue"

// export const useDebounce = <T>(func: IDebounce<T>, delay: number) => {
//   let timer: NodeJS.Timeout | null = null

//   return function f(this: void, ...args: T[]) {
//     if (timer) {
//       clearTimeout(timer)
//     }
//     timer = setTimeout(() => {
//       func.call(this, ...args)
//     }, delay)
//   }
// }

import { type Ref, ref, watch, type UnwrapRef, onUnmounted } from 'vue'

export const useDebounce = <T>(value: Ref<T>, delay: number) => {
  const debounceValue = ref(value.value)
  let timer: NodeJS.Timeout | null = null
  const unwatch = watch(value, (newVal) => {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      debounceValue.value = newVal as UnwrapRef<T>
    }, delay)
  })

  // 释放内存销毁监听器
  onUnmounted(() => {
    unwatch()
  })
  return debounceValue
}
